package com.hw.service.basic;

import cn.hutool.core.img.ImgUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hw.entity.dto.basic.StoreInfoDTO;
import com.hw.entity.po.basic.Food;
import com.hw.entity.po.basic.StoreInfo;
import com.hw.entity.query.basic.StoreInfoQuery;
import com.hw.entity.vo.basic.FoodVO;
import com.hw.entity.vo.basic.StoreInfoVO;
import com.hw.mapper.basic.StoreInfoMapper;
import com.hw.model.ResponseResult;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * 菜单 Service实现类
 *
 * @author whw
 * @date 2021-06-21
 */
@Service
public class StoreInfoServiceImpl extends ServiceImpl<StoreInfoMapper, StoreInfo> implements StoreInfoService {

    @Autowired
    // 因为在foodService也有调用storeInfoService，所以不加上懒加载，会出现循环依赖报错
    @Lazy(true)
    private FoodService foodService;

    /**
     * 获取列表
     *
     * @param query
     * @return
     */
    @Override
    public List<StoreInfoVO> list(StoreInfoQuery query) {
        QueryWrapper<StoreInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("c_deleted", 0)
                .like(StringUtils.isNoneBlank(query.getStoreName()), "c_store_name", query.getStoreName());
        // 从数据库取出来的图片都是byte[]类型，所以不能直接返回，需要处理一下
        //        for (StoreInfoVO vo : list) {
//            // 处理头像
//            if (ArrayUtils.isNotEmpty(vo.getImg())) {
//                String avatarBase64 = ImgUtil.toBase64(ImgUtil.toImage(vo.getImg()), "png");
//                vo.setImgVO(avatarBase64);
//                // 一个vo带一个图片信息就够了，重复的去掉
//                vo.setImg(null);
//            }
//        }
        return baseMapper.list(queryWrapper);
    }

    /**
     * 保存
     *
     * @param dto
     */
    @Override
    public ResponseResult<?> save(StoreInfoDTO dto) {
        String storeInfoId = dto.getStoreId();
        QueryWrapper<StoreInfo> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isBlank(storeInfoId)) {
            // 新增
            StoreInfo po = new StoreInfo();
            BeanUtils.copyProperties(dto, po);
            // 判断是否名字重复
            queryWrapper
                    .eq("c_store_name", po.getStoreName())
                    .eq("c_deleted", 0);
            StoreInfo temp = baseMapper.selectOne(queryWrapper);
            // 如果查询出id不同，名称相同的另一个商家
            if (temp != null && !temp.getStoreId().equals(po.getStoreId())) {
                return ResponseResult.error("已存在该商家，新增失败!");
            }
            po.setStoreId(UUID.randomUUID().toString());
            save(po);
            return ResponseResult.success();
        } else {
            // 编辑
            StoreInfo storeInfo = getById(dto.getId());
            if (ObjectUtils.isNotEmpty(storeInfo)) {
                BeanUtils.copyProperties(dto, storeInfo);
            }
            // 判断是否名字重复
            queryWrapper
                    .eq("c_store_name", storeInfo.getStoreName())
                    .eq("c_deleted", 0);
            StoreInfo temp = baseMapper.selectOne(queryWrapper);
            // 如果查询出id不同，名称相同的另一个商家
            if (temp != null && !temp.getStoreId().equals(storeInfo.getStoreId())) {
                return ResponseResult.error("名字不能与其他商家重复，更新失败!");
            }
            updateById(storeInfo);
            return ResponseResult.success();
        }
    }

    /**
     * 删除
     *
     * @param storeId
     */
    @Override
    public ResponseResult<?> delete(String storeId) {
        if (StringUtils.isNotBlank(storeId)) {
            // 先更新当前商家的菜品删除状态
            UpdateWrapper<Food> foodUpdateWrapper = new UpdateWrapper<>();
            foodUpdateWrapper
                    .set("c_deleted", 1)
                    .eq("c_store_id", storeId);
            foodService.update(foodUpdateWrapper);
            UpdateWrapper<StoreInfo> storeUpdateWrapper = new UpdateWrapper<>();
            storeUpdateWrapper
                    .set("c_deleted", 1)
                    .eq("c_store_id", storeId);
            update(storeUpdateWrapper);
            return ResponseResult.success();
        }
        return ResponseResult.error();
    }

    /**
     * 获取详情
     *
     * @param storeId
     * @return
     */
    @Override
    public StoreInfoVO getDetail(String storeId) {
        if (StringUtils.isBlank(storeId)) {
            return null;
        }
        StoreInfoVO vo = new StoreInfoVO();
        QueryWrapper<StoreInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("c_store_id", storeId)
                .eq("c_deleted", 0);
        StoreInfo po = getOne(queryWrapper);
        BeanUtils.copyProperties(po, vo);
        // 处理头像
//        if (ArrayUtils.isNotEmpty(po.getImg())) {
//            String avatarBase64 = ImgUtil.toBase64(ImgUtil.toImage(po.getImg()), "png");
//            vo.setImgVO(avatarBase64);
//            vo.setImg(null);
//        }
        return vo;
    }

    /**
     * 保存图片
     *
     * @param file
     * @param storeId
     */
    @Override
    public void updateAvatar(MultipartFile file, String storeId) {
        try {
            byte[] bytes = file.getBytes();
            UpdateWrapper<StoreInfo> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("c_img", bytes)
                    .eq("c_store_id", storeId);
            update(updateWrapper);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
